import request from './request';

const getEnvPath = function(){
    let path = localStorage.getItem('domain');
    path = path
            //去掉协议
            .replace(/^(https?:\/\/)|(\/)$/g, '')
            //去掉端口
            .replace(/:[0-9]+$/g, '')

    //排除线上
    if(!/^cloud\./.test(path)){
        path = path.replace(/^[^.]+\./g, '')
    }

    return path
}

const login = function(source, isAdd){
    return new Promise((resolve, reject) => {
        const img = document.createElement('img');
        img.src = localStorage.getItem('domain') + 'jz/user/allow/imageCode.do?type=2&_=' + new Date().getTime();
        img.style.display = 'none';
        document.body.appendChild(img);
        img.onload = ()=>{
            const code = recognise(img)
            img.remove()
            const {password, username} = source;
            const params = {
                username,
                password,
                code
            }
            request.post('login', params).then(res => {
                if(res.status === 200){
                    const {versionType, newUser} = res.data;
                    if(versionType == 1){
                        let users = JSON.parse(localStorage.getItem('users') || '[]')
                        delete params.code;
                        const envPath = getEnvPath();
                        users = users.map(v => {
                            delete v.active
                            if(!isAdd && v.username === username){
                                v.active = true
                            }
                            return v
                        })
                        //如果添加的用户在当前用户里存在，那么先移除
                        //新添加的用户将在列表最上面
                        if(isAdd){
                            users = users.filter(v => {
                                return v.username !== username && v.realname != ''
                            })
                            params.active = true;
                            params.envPath = envPath;
                            users.unshift(params);
                        }
                        resolve(users)
                    }
                    else if(newUser){
                        reject('该帐号需完善信息，请登录网页查看')
                    }
                    else{
                        reject('云记账助手仅支持代账用户')
                    }
                }
                else{
                    reject(res.message)
                }
            }).catch(err => {
                reject(err)
            })
        }
        img.onerror = ()=>{
            reject('系统异常，请重试')
        }
    })
}

export {
    getEnvPath,
    login
}